package com.example.mvvmcore.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import com.example.mvvmcore.view.BaseActivity;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class BaseFragment extends Fragment {
    /**
     * 是否初始化
     */
    private Boolean isInit=false;

    /**
     * 是否加载完成
     */
    private Boolean isLoaded=false;
    private View mView;

    private Map<Integer,Object> varMap=new ConcurrentHashMap<Integer,Object>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        isInit=true;
//        mView = inflater.inflate(getLayoutId(),container,false);
        initEnv();
        preparVarMap(varMap);
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);

        if (varMap.size()>0){
            for (Map.Entry<Integer,Object> entry:varMap.entrySet()){
                binding.setVariable(entry.getKey(),entry.getValue());
            }
        }

        return binding.getRoot();//super.onCreateView(inflater, container, savedInstanceState);
    }

    protected abstract void initEnv();

    protected abstract int getLayoutId();

    protected abstract void preparVarMap(Map<Integer, Object> map);




    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        preparLoadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit=false;
        isLoaded=false;
    }

    /**
     * 准备加载数据
     */
    private void preparLoadData() {
        if (!isInit){return;}
        if (getUserVisibleHint()){
            lazyLoad();
            isLoaded=true;
        }else{
            if (isLoaded){
                stopLoad();
            }
        }
    }

    protected <T extends View> T $(int resId){
        return mView.findViewById(resId);
    }

    /**
     * 停止延时加载
     */
    protected abstract void stopLoad();

    /**
     * 延时加载
     */
    protected abstract void lazyLoad();

    /**
     * 显示消息
     */
    protected void showMsg(String msg){
        BaseActivity activity=(BaseActivity)getActivity();
        if (null!=activity){
            activity.showMsg(msg);
        }
    }

    /**
     * 获取BaseActivity
     */
    protected BaseActivity getBaseActivity(){
        return (BaseActivity) getActivity();
    }





}
